import asyncRoutes from "@/router/routes-async.js";

/**
 * str 字符串
 *  a       ['a']
 *  a_1     ['a', 'a_1']
 *  a_1_2   ['a', 'a_1', 'a_1_2']
 */
function split(str) {
  let arr = str.split("_"); // 分割成数组

  // console.log("arr", arr);
  const result = arr.reduce((prev, item, index) => {
    // console.log(prev, item, index);
    if (index === 0) {
      prev.push(item);
    } else {
      // 追加进去的是数组prev上一个的内容拼接上当前的item
      prev.push(`${prev[index - 1]}_${item}`);
    }

    return prev;
  }, []);

  // console.log("result", result);
  return result;
}

function genMenuItems(routes, checkedKeys) {
  return routes
    .filter((route) => checkedKeys.includes(route.name))
    .map((route) => {
      // 会修改到route这个对象，避免修改到原数据，做个拷贝
      const curRoute = { ...route };

      // 判断 curRoute 是否有 children
      if (curRoute.children) {
        // 递归
        curRoute.children = genMenuItems(curRoute.children, checkedKeys);
      }

      return curRoute;
    });
}

export default {
  namespaced: true,

  state() {
    return {
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
    };
  },

  getters: {
    token(state) {
      // return state.userInfo ? state.userInfo.token : undefined;
      // 可选链 ?.  ??
      return state.userInfo?.token;
    },

    role(state) {
      return state.userInfo?.role;
    },

    permissions(state) {
      return state.userInfo?.checkedkeys;
    },

    /**
     * 当前用户的左侧菜单数据
     * 基于用户权限与用户角色和asyncRoutes
     */
    menuItems(state) {
      // 0. 取出当前用户的角色
      const role = state.userInfo?.role;
      if (role === 2) {
        // 超级管理员，直接拥有所有权限
        return asyncRoutes;
      }

      // 1. 取出当前用户的权限集合
      const checkedKeys = state.userInfo?.checkedkeys; // ['a']
      // 2. 对档期那用户的权限集合做个处理，得到 allCheckedKeys
      const allCheckedKeys = [];
      checkedKeys.forEach((key) => {
        allCheckedKeys.push(...split(key));
      });
      // console.log("checkedKeys", checkedKeys);
      console.log("allCheckedKeys", allCheckedKeys);
      // 3. 过滤 asyncRoutes
      const result = genMenuItems(asyncRoutes, allCheckedKeys);
      // 4. return result
      return result;
    },
  },

  mutations: {
    set_userInfo(state, payload) {
      state.userInfo = payload;

      // 写入 localStorag
      localStorage.setItem("userInfo", JSON.stringify(payload));
    },
  },
};
